package com.google.samples.apps.viewmodel.communication

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.samples.apps.viewmodel.MainActivity
import com.google.samples.apps.viewmodel.R
import kotlinx.android.synthetic.main.fragment_c1.*

/**
 * A simple [Fragment] subclass.
 * Use the [CFragment2.newInstance] factory method to
 * create an instance of this fragment.
 */
class CFragment2 : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_c1, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        text.text = "fragment 2"

        val shareViewModel = ViewModelProvider(context as MainActivity)
            .get(ShareViewModel::class.java)
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                shareViewModel.seekBarLiveData.value = progress
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }
        })
        shareViewModel.seekBarLiveData.observe(CFragment2@ this, Observer {
            seekBar.setProgress(it)
        })
    }

    companion object {

        @JvmStatic
        fun newInstance() =
            CFragment2().apply {
            }
    }
}